import Vue from 'vue';
import Router from 'vue-router';
import routes from './routers';
import store from '@/store';
import Watermark from '@/libs/watermark.js';
import {setWaterMark} from '../../config/loginConfig';
import { getCookies } from '../utils/utils';
//获取原型对象上的push函数
import { clearLoginStorage } from '../utils/tools';
Vue.use(Router);
// 重复点击相同路由报错问题
const originalPush = Router.prototype.push;
const originReplace = Router.prototype.replace;
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
    return originalPush.call(this, location);
};
//修改原型对象中的replace方法
Router.prototype.replace = function push(location) {
    return originReplace.call(this, location).catch(err => err);
};
const router = new Router({
    base: process.env.NODE_ENV === 'production_app' ? '/' : '/mobile/',
    routes,
    mode: process.env.NODE_ENV === 'production_app' ? 'hash' : 'hash'
});

router.onError((error) => {
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    if (isChunkLoadFailed) {
        // 用路由的replace方法，并没有相当于F5刷新页面，失败的js文件并没有从新请求，会导致一直尝试replace页面导致死循环，而用 location.reload 方法，相当于触发F5刷新页面，虽然用户体验上来说会有刷新加载察觉，但不会导致页面卡死及死循环，从而曲线救国解决该问题
        location.reload();
    }
});

const LOGIN_PAGE_NAME = '/loginIndex';//登录页面
const FORGET_PWD = '/forgetPwd';//忘记密码页面
const WX_LOGIN = '/wxLogin'; // 微信单点登录页面
const BINGING = '/binging'; // 绑定页面
// 二维码相关页面【主页面，事件处理页面，证书预览页面（扫码）】
const QRCODE_PAGES = ['/qrcode/index', '/qrcode/event-handling', '/qrcode/preview-certificate']; // 二维码相关页面
let isInitWaterMark = false;
router.beforeEach((to, from, next) => {
    /* 路由发生变化修改页面meta */
    let head = document.getElementsByTagName('head');
    let metaList = document.getElementsByTagName('meta');
    const lastPath = to.fullPath;
    const isToken = to.query.access_token;
    const examIframeToken = to.query.examIframeToken;
    for (var i = 0; i < metaList.length; i++) {
        if (metaList[i].name === 'viewport') {
            head[0].removeChild(metaList[i]);
        }
    }
    if (to.name !== 'pkEnter' && to.name !== 'pkBorad') {
        let meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover';
        head[0].appendChild(meta);
        let html = document.getElementsByTagName('html');
        let body = document.getElementsByTagName('body');
        body[0].removeAttribute('style');
        html[0].removeAttribute('style');
        html[0].removeAttribute('data-dpr');
    } else {
        let html = document.getElementsByTagName('html');
        let dataDpr = store.state.config.dataDpr;
        let hfont = store.state.config.pkHtmlFontSize;
        if (dataDpr && dataDpr !== 1) {
            let metaEl = document.createElement('meta');
            metaEl.setAttribute('name', 'viewport');
            let scale = 1 / dataDpr;
            metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no, viewport-fit=cover');
            head[0].appendChild(metaEl);
            // html[0].style.fontSize = hfont;
            // html[0].addAttribute('data-dpr', dataDpr);
        }
    }
    if (window.localStorage.getItem('token') && (window.localStorage.getItem('token') === 'undefined' || window.localStorage.getItem('token') === 'null')) {
        window.localStorage.removeItem('token');
    }
    const token = window.localStorage.getItem('token');
    if (!token && !isToken && !examIframeToken && (to.path === LOGIN_PAGE_NAME || to.path === WX_LOGIN || to.path === BINGING || to.path === FORGET_PWD || QRCODE_PAGES.includes(to.path))) {
        //未登陆且要跳转的页面是登录页
        next(); //跳转
    } else if (!token && !isToken && !examIframeToken) {
        //未登录且要跳转的页面不是登录页
        window.localStorage.setItem('lastPath', lastPath);
        next({
            path: LOGIN_PAGE_NAME //跳转到登录页
        });
    } else if (!token && isToken && !examIframeToken && window.localStorage.getItem('authFail') && to.path === LOGIN_PAGE_NAME) {
        window.localStorage.removeItem('authFail');
        next();
    } else if ((!token && isToken) || (token && isToken && !window.sessionStorage.getItem('firstLogin'))) {
        // 若无token有isToken或有oken且有isToken不存在firstLogin session时。则重新进行单点登录（防止切换用户登录仍是原用户的问题）
        if (!window.sessionStorage.getItem('firstLogin')) {
            clearLoginStorage();
        }
        if (from.path === LOGIN_PAGE_NAME) {
            next();
        }
        // 单点登录
        store.dispatch('handleTokenLogin', {
            token: isToken
        }).then(res => {
            if (res.data.code === 200) {
                // delete to.query.access_token;
                var localStorage = window.localStorage;
                localStorage.setItem('token', res.data.result.token);
                localStorage.setItem('loginUser', res.data.result.usrEntId);
                window.sessionStorage.setItem('firstLogin', true);
                if (to.path === LOGIN_PAGE_NAME) {
                    next({
                        path: '/home' //跳转到homeName页
                    });
                } else {
                    next({
                        path: to.path,
                        replace: true,
                        query: to.query
                    });
                }
            } else {
                if (res && res.data && res.data.msg) {
                    alert(res.data.msg);
                }
                clearLoginStorage();
                window.localStorage.setItem('authFail', true);
                next({
                    path: LOGIN_PAGE_NAME //跳转到登录页
                });
            }
        }).catch(() => {
            clearLoginStorage();
            window.localStorage.setItem('authFail', true);
            next({
                path: LOGIN_PAGE_NAME //跳转到登录页
            });
        });
    } else if (token && to.path === LOGIN_PAGE_NAME) {
        //已登录且要跳转的页面是登录页
        next({
            path: '/home' //跳转到homeName页
        });
    } else {
        let userName = window.localStorage.getItem('usrSteUsrId') ? window.localStorage.getItem('usrSteUsrId') : '';
        let waterMarkSwitch = window.localStorage.getItem('waterMarkSwitch') ? window.localStorage.getItem('waterMarkSwitch') : '';
        if (waterMarkSwitch === 'ON') {
            Watermark.set(userName);
        }
        next();
        /*TODO
        store.dispatch('getUserInfo').then(user => {
            next();
        }).catch(() => {
            next({
                path: LOGIN_PAGE_NAME
            });
        });*/
    }
});
router.afterEach(to => {
    window.scrollTo(0, 0);
});

export default router;
